package com.xoa.global.proxy.TriggerUtils;

import com.xoa.global.proxy.ProxyHandle;
import com.xoa.global.proxy.SpringContextUtil;
import com.xoa.global.proxy.TriggerSubject;
import com.xoa.model.workflow.TriggerPlugIn;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Constructor;
import java.lang.reflect.Proxy;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by pfl on 2017/7/29.
 */
public class Trigger {
    public static  ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    public static void run(final String clazzName,final String company,final Object ...agrs){
        // 子线程 共享主线程的 request（只针对于主线程结束前子线程可以使用，否则主线程结束  request 将被销毁）
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        RequestContextHolder.setRequestAttributes(servletRequestAttributes,true);
        TriggerPlugIn tri = (TriggerPlugIn) agrs[0];
        CountDownLatch countDownLatch = new CountDownLatch(tri.isSync() ? 1:0);
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try{
                    Class clazz = Class.forName(clazzName);
                    ApplicationContext ac = SpringContextUtil.getApplicationContext();
                    TriggerSubject a=(TriggerSubject) Proxy.newProxyInstance(TriggerSubject.class.getClassLoader(),
                            new Class[]{TriggerSubject.class},
                            new ProxyHandle(ac.getBean(clazz)));
                    a.doRun(company,agrs);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(tri.isSync())countDownLatch.countDown();
                }
            }
        });
        if(tri.isSync()) {
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
